<template>
  <div class="vote-active">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>进行中投票</span>
          <el-button type="primary" @click="handleAdd">发起投票</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="投票标题">
          <el-input v-model="searchForm.title" placeholder="请输入投票标题" />
        </el-form-item>
        <el-form-item label="投票类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型">
            <el-option label="宠物评选" value="pet" />
            <el-option label="活动投票" value="activity" />
            <el-option label="满意度调查" value="survey" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 投票列表 -->
      <el-table :data="voteList" border style="width: 100%">
        <el-table-column prop="title" label="投票标题" min-width="200" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalVotes" label="参与人数" width="100" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleStatistics(scope.row)">
              统计
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleEnd(scope.row)"
              v-if="!isEnded(scope.row)"
            >
              结束
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发起投票对话框 -->
    <el-dialog
      title="发起投票"
      v-model="dialogVisible"
      width="700px"
    >
      <el-form :model="voteForm" :rules="rules" ref="voteFormRef" label-width="100px">
        <el-form-item label="投票标题" prop="title">
          <el-input v-model="voteForm.title" placeholder="请输入投票标题" />
        </el-form-item>
        <el-form-item label="投票类型" prop="type">
          <el-select v-model="voteForm.type" placeholder="请选择投票类型">
            <el-option label="宠物评选" value="pet" />
            <el-option label="活动投票" value="activity" />
            <el-option label="满意度调查" value="survey" />
          </el-select>
        </el-form-item>
        <el-form-item label="投票时间" prop="dateRange">
          <el-date-picker
            v-model="voteForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="投票选项" prop="options">
          <div v-for="(option, index) in voteForm.options" :key="index" class="option-item">
            <el-input v-model="option.content" placeholder="请输入选项内容">
              <template #append>
                <el-upload
                  class="option-upload"
                  action="#"
                  :show-file-list="false"
                  :on-change="(file) => handleImageUpload(file, index)"
                >
                  <el-button type="primary">上传图片</el-button>
                </el-upload>
              </template>
            </el-input>
            <el-image
              v-if="option.image"
              :src="option.image"
              class="option-image"
              fit="cover"
            />
            <el-button 
              type="danger" 
              circle 
              @click="removeOption(index)"
              v-if="voteForm.options.length > 2"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          <div class="add-option">
            <el-button type="primary" link @click="addOption">
              <el-icon><Plus /></el-icon>
              添加选项
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="投票说明">
          <el-input 
            type="textarea" 
            v-model="voteForm.description" 
            rows="3"
            placeholder="请输入投票说明"
          />
        </el-form-item>
        <el-form-item label="投票设置">
          <el-checkbox v-model="voteForm.settings.multipleChoice">允许多选</el-checkbox>
          <el-checkbox v-model="voteForm.settings.needLogin">需要登录</el-checkbox>
          <el-checkbox v-model="voteForm.settings.showResult">实时显示结果</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  title: '',
  type: ''
})

// 投票列表数据
const voteList = ref([
  {
    id: 1,
    title: '2024年最可爱宠物评选',
    type: '宠物评选',
    totalVotes: 1280,
    startTime: '2024-03-18 00:00:00',
    endTime: '2024-03-25 23:59:59',
    options: [
      { content: '金毛-Lucky', image: 'https://placeholder.com/100', votes: 520 },
      { content: '布偶猫-Mimi', image: 'https://placeholder.com/100', votes: 480 },
      { content: '柯基-Coco', image: 'https://placeholder.com/100', votes: 280 }
    ]
  },
  {
    id: 2,
    title: '宠物医疗服务满意度调查',
    type: '满意度调查',
    totalVotes: 368,
    startTime: '2024-03-15 00:00:00',
    endTime: '2024-03-20 23:59:59',
    options: [
      { content: '非常满意', votes: 200 },
      { content: '满意', votes: 120 },
      { content: '一般', votes: 48 }
    ]
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 发起投票对话框
const dialogVisible = ref(false)
const voteFormRef = ref(null)

const voteForm = reactive({
  title: '',
  type: '',
  dateRange: [],
  options: [
    { content: '', image: '' },
    { content: '', image: '' }
  ],
  description: '',
  settings: {
    multipleChoice: false,
    needLogin: true,
    showResult: true
  }
})

const rules = {
  title: [{ required: true, message: '请输入投票标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择投票类型', trigger: 'change' }],
  dateRange: [{ required: true, message: '请选择投票时间', trigger: 'change' }],
  options: [{ required: true, message: '请至少添加两个选项', trigger: 'change' }]
}

// 方法定义
const handleSearch = () => {
  ElMessage.success('搜索功能待实现')
}

const resetSearch = () => {
  searchForm.title = ''
  searchForm.type = ''
}

const getStatusType = (row) => {
  const now = new Date().getTime()
  const start = new Date(row.startTime).getTime()
  const end = new Date(row.endTime).getTime()
  
  if (now < start) return 'info'
  if (now > end) return 'danger'
  return 'success'
}

const getStatusText = (row) => {
  const now = new Date().getTime()
  const start = new Date(row.startTime).getTime()
  const end = new Date(row.endTime).getTime()
  
  if (now < start) return '未开始'
  if (now > end) return '已结束'
  return '进行中'
}

const isEnded = (row) => {
  return new Date().getTime() > new Date(row.endTime).getTime()
}

const handleAdd = () => {
  voteForm.title = ''
  voteForm.type = ''
  voteForm.dateRange = []
  voteForm.options = [
    { content: '', image: '' },
    { content: '', image: '' }
  ]
  voteForm.description = ''
  voteForm.settings = {
    multipleChoice: false,
    needLogin: true,
    showResult: true
  }
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.success('查看投票详情')
}

const handleStatistics = (row) => {
  ElMessage.success('查看投票统计')
}

const handleEnd = (row) => {
  ElMessageBox.confirm('确认结束该投票吗？结束后将不能再投票', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('投票已结束')
  })
}

const addOption = () => {
  voteForm.options.push({ content: '', image: '' })
}

const removeOption = (index) => {
  voteForm.options.splice(index, 1)
}

const handleImageUpload = (file, index) => {
  // 这里应该实现图片上传逻辑
  voteForm.options[index].image = URL.createObjectURL(file.raw)
}

const submitForm = async () => {
  if (!voteFormRef.value) return
  
  await voteFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('投票创建成功')
      dialogVisible.value = false
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.option-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.add-option {
  margin-top: 10px;
}

:deep(.el-upload) {
  width: 100%;
}
</style> 